/**
 * @class UI-条目组件-信息弹出条
 * @author DuskyHuang 圣子
*/

import { _decorator, Label, UITransform, Vec2, Component, Color } from 'cc';
const { ccclass } = _decorator;
import { utils, TweenSwitcher, core } from 'cfw';
import { UI } from 'notifications';
import { LabelI18n } from '../label-i18n';
const { serialize, tip } = utils;

@ccclass('cocosmos.pop-info-line')
export class PopInfoLine extends Component {

    @tip("内容文本", LabelI18n) public i18n: LabelI18n;
    @tip("保持时间", ['unit', 'sec']) public duration: time.sec = 1;
    @serialize _margins: Vec2 = new Vec2(20, 10);
    @tip("留边宽高")
    public get margins(): Vec2 { return this._margins; }
    public set margins(args: Vec2) {
        this._margins = args;
        this.scheduleOnce(() => {
            const { x, y } = this._margins;
            const { width, height } = this.i18n.getComponent(UITransform).contentSize;
            this.i18n.node?.parent?.getComponent(UITransform).setContentSize(width + x, height + y);
        });
    }

    private _tws: TweenSwitcher;
    private _label: Label;

    protected onLoad(): void {
        this._tws = this.getComponent(TweenSwitcher) ??
            this.getComponentInChildren(TweenSwitcher) ??
            this.addComponent(TweenSwitcher);
        this._label = this.i18n.getComponent(Label);
        core.on(UI.Popups.INFO_LINE, this.onPopInfo, this);
        core.on(UI.Popups.TIP_LINE, this.onTipInfo, this);
    }

    protected start(): void {
        this._tws.node.active = false;
    }

    protected onDestroy(): void { core.unload(this); }

    private onPopInfo(chars: i18nKey, dur?: time.sec): void {
        this._label.color = Color.WHITE;
        this.show(chars, dur);
    }

    private onTipInfo(chars: i18nKey, dur?: time.sec): void {
        this._label.color = TIP_COLOR;
        this.show(chars, dur);
    }

    public show(chars: i18nKey, duration?: time.sec): void {
        this.unscheduleAllCallbacks();
        this.i18n.string = chars;
        const dur = duration ?? this.duration;
        this._tws.show(true);
        this.scheduleOnce(() => this._tws.hide(true), dur);
    }
}

const TIP_COLOR = new Color(153, 153, 63);